package cn.com.aiton.educenter.controller;

import cn.com.aiton.educenter.client.DictionaryClient;
import cn.com.aiton.educenter.config.OperLog;
import cn.com.aiton.educenter.entity.PestsControl;
import cn.com.aiton.educenter.entity.PestsTrap;
import cn.com.aiton.educenter.entity.UcenterMember;
import cn.com.aiton.educenter.entity.vo.*;
import cn.com.aiton.educenter.service.PestsControlService;
import cn.com.aiton.educenter.service.PestsQrcodeService;
import cn.com.aiton.educenter.service.PestsTrapService;
import cn.com.aiton.educenter.service.UcenterMemberService;
import cn.com.qiter.common.Result;
import cn.com.qiter.common.vo.PestsTrapModel;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 诱捕器业务数据表 前端控制器
 * </p>
 *
 * @author testAuthor
 * @since 2021-03-11
 */
@Log4j2
@RestController
@RequestMapping("/educenter/trap")
public class PestsTrapController {
    //把service注入
    @Autowired
    private PestsTrapService pestsTrapService;

    @Autowired
    private DictionaryClient dictionaryClient;
    @Autowired
    private PestsQrcodeService pestsQrcodeService;
    @Autowired
    private UcenterMemberService ucenterMemberService;
    //1 查询讲师表所有数据
    //rest风格

    @ApiOperation(value = "查询所有诱捕器")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "查询所有诱捕器")
    @GetMapping("findAll")
    public Result findAll() {
        //调用service的方法实现查询所有的操作
        List<PestsTrap> list = pestsTrapService.list(null);
        return Result.ok().data("items",list);
    }

    //2 逻辑删除讲师的方法
    @ApiOperation(value = "根据ID删除")
    @OperLog(type = "删除",module = "PestsTrapController",requestDes = "根据ID删除")
    @DeleteMapping("remove/{id}")
    public Result remove(@ApiParam(name = "id", value = "ID", required = true)
                                @PathVariable String id) {
        boolean flag = pestsTrapService.removeById(id);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //3 分页查询讲师的方法
    //current 当前页
    //limit 每页记录数
    @ApiOperation(value = "分页查询诱捕器")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "分页查询所有诱捕器")
    @GetMapping("page/{current}/{limit}")
    public Result page(@PathVariable long current,
                       @PathVariable long limit) {
        //创建page对象
        Page<PestsTrap> page = new Page<>(current,limit);

        //调用方法实现分页
        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
        pestsTrapService.page(page,null);

        long total = page.getTotal();//总记录数
        List<PestsTrap> records = page.getRecords(); //数据list集合

        return Result.ok().data("total",total).data("rows",records);
    }

    //4 条件查询带分页的方法
    @ApiOperation(value = "分页查询所有诱捕器")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "分布查询所有诱捕器")
    @PostMapping("pageCondition/{current}/{limit}")
    public Result pageCondition(@PathVariable long current, @PathVariable long limit,
                                       @RequestBody(required = false) PestsTrapQuery query) {
        //创建page对象
        Page<PestsTrap> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<PestsTrap> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = query.getDeviceId();
        String begin = query.getBegin();
        String end = query.getEnd();
        String qrcode = query.getQrcode();
        String userId = query.getUserId();
        String projectId = query.getProjectId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }
        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(qrcode)) {
            wrapper.eq("qrcode",qrcode);
        }
        //排序
        wrapper.orderByDesc("stime");

        //调用方法实现条件查询分页
        pestsTrapService.page(pageTeacher,wrapper);
        log.error(pageTeacher.getPages());
        log.error(pageTeacher.getSize());
        long pages = pageTeacher.getPages();
        long size = pageTeacher.getSize();
        log.error(pageTeacher.getCountId());
        log.error(pageTeacher.getMaxLimit());

        long total = pageTeacher.getTotal();//总记录数
        List<PestsTrap> records = pageTeacher.getRecords(); //数据list集合
        List<PestsTrapVo> record = new ArrayList<>();
        for (PestsTrap pc :
                records) {
            PestsTrapVo vo = new PestsTrapVo();
            BeanUtil.copyProperties(pc,vo);
            vo.setPestsQrcode(pestsQrcodeService.getByQrcode(pc.getQrcode()));
            vo.setUcenterMember(ucenterMemberService.getById(pc.getUserId()));
            record.add(vo);
        }
        return Result.ok().data("total",total).data("pages",pages).data("size",size).data("rows",record);
    }

    //添加讲师接口的方法
    @ApiOperation(value = "新增加数据")
    @OperLog(type = "新增",module = "PestsTrapController",requestDes = "新增诱捕器")
    @PostMapping("add")
    public Result add(@RequestBody PestsTrapModel eduTeacher) {
        PestsTrap trap = new PestsTrap();
        BeanUtils.copyProperties(eduTeacher,trap);
        Date stime = DateUtil.parse(eduTeacher.getStime(), "yyyy-MM-dd HH:mm:ss");
        trap.setStime(stime);

        String str = eduTeacher.getUserId();
        UcenterMember pestsProject = ucenterMemberService.getById(str);
        trap.setProjectId(pestsProject.getProjectId());
        boolean save = pestsTrapService.save(trap);
        if(save) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //根据讲师id进行查询
    @ApiOperation(value = "根据字典名称查询数据")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "根据名曲名称查询数据")
    @GetMapping("getDictByName/{name}")
    public Result getDictByName(@PathVariable String name) {
        Result result = dictionaryClient.getByName(name);
        return Result.ok().data("dict",result);
    }
    //根据讲师id进行查询
    @ApiOperation(value = "根据ID查询数据")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "根据ID查询一条数据")
    @GetMapping("get/{id}")
    public Result get(@PathVariable String id) {
        PestsTrap eduTeacher = pestsTrapService.getById(id);
        return Result.ok().data("teacher",eduTeacher);
    }
    //根据讲师id进行查询
    @ApiOperation(value = "根据二维码查询数据")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "根据二维码查询数据")
    @GetMapping("getByQrcode/{qrcode}")
    public Result getByQrcode(@PathVariable String qrcode) {
        QueryWrapper<PestsTrap> wrapper = new QueryWrapper<>();
        wrapper.eq("qrcode",qrcode);
        //wrapper.last("LIMIT 1");
        List<PestsTrap> eduTeacher = pestsTrapService.list(wrapper);
        return Result.ok().data("trap",eduTeacher);
    }
    //讲师修改功能
    @ApiOperation(value = "更新数据")
    @OperLog(type = "更新",module = "PestsTrapController",requestDes = "更新数据")
    @PostMapping("update")
    public Result update(@RequestBody PestsTrap eduTeacher) {
        boolean flag = pestsTrapService.updateById(eduTeacher);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}")
    public Result countDay(@PathVariable String day , @PathVariable String projectId) {
        Integer count = pestsTrapService.countDayByProjectId(day,projectId);
        return Result.ok().data("countDay",count);
    }
    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计")
    @OperLog(type = "统计",module = "PestsControlController",requestDes = "统计防治的方法")
    @GetMapping("countDay/{day}/{projectId}/{memberId}")
    public Result countDay(@PathVariable String day,@PathVariable String projectId,@PathVariable String memberId) {
        Integer count = pestsTrapService.countDayByProjectIdAndMemberId(day,projectId,memberId);
        return Result.ok().data("countDay",count);
    }

    /**
     *
     * @param day
     * @return
     */
    @ApiOperation(value = "统计数据")
    @OperLog(type = "功能",module = "PestsTrapController",requestDes = "统计")
    @GetMapping("countDay/{day}")
    public Result countDay(@PathVariable String day) {
        Integer count = pestsTrapService.countDay(day);
        return Result.ok().data("countDay",count);
    }

    /**
     *
     * @param
     * @return
     */
    @ApiOperation(value = "统计数据")
    @OperLog(type = "功能",module = "PestsTrapController",requestDes = "统计数据")
    @GetMapping("countTrapAll")
    public Integer countTrapAll() {
        Integer count = pestsTrapService.getBaseMapper().selectCount(null);
        return count;
    }
    /**
     *  统计某个项目下的Trap记录数
     * @param projectId
     * @return
     */
    @ApiOperation(value = "统计数据")
    @OperLog(type = "功能",module = "PestsTrapController",requestDes = "统计数据")
    @GetMapping("countTrapByProjectId/{projectId}")
    public Result countPestsByProjectId(@PathVariable String projectId) {
        Integer count = pestsTrapService.countTrapByProjectId(projectId);
        return Result.ok().data("count",count);
    }
    /**
     * 后台管理系统，查看记录时，按code_int 排序进行
     * @param current
     * @param limit
     * @param query
     * @return
     */
    @ApiOperation(value = "分页查询所有诱捕器")
    @OperLog(type = "查询",module = "PestsTrapController",requestDes = "分页查询所有诱捕器")
    @PostMapping("pageTrapAndQrcode/{current}/{limit}")
    public Result pageTrapAndQrcode(@PathVariable long current, @PathVariable long limit,
                                     @RequestBody(required = false) PestsTrapQuery query) {
        //创建page对象
        Page<TrapQrcodeVo> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<PestsTrap> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = query.getDeviceId();
        String begin = query.getBegin();
        String end = query.getEnd();
        String userId = query.getUserId();
        String qrcode = query.getQrcode();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("c.stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("c.stime",end);
        }
        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("c.user_id",userId);
        }
        if(!StringUtils.isEmpty(qrcode)) {
            wrapper.eq("qrcode",qrcode);
        }
        //排序
        wrapper.orderByDesc("code_int");
        //调用方法实现条件查询分页
        pestsTrapService.pageTrapAndQrcode(pageTeacher,wrapper);
        long total = pageTeacher.getTotal();//总记录数
        List<TrapQrcodeVo> records = pageTeacher.getRecords(); //数据list集合
        return Result.ok().data("total",total).data("rows",records);
    }
}

